﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Controls;
using System.Windows.Documents;

namespace CodeStash.Addin.Behaviours
{
    public class DataGridAttachProps
    {
        #region HyperlinkCommand

        /// <summary>
        /// HyperlinkCommand Attached Dependency Property
        /// </summary>
        public static readonly DependencyProperty HyperlinkCommandProperty =
            DependencyProperty.RegisterAttached("HyperlinkCommand", typeof(ICommand), typeof(DataGridAttachProps),
                new FrameworkPropertyMetadata((ICommand)null,
                    new PropertyChangedCallback(OnHyperlinkCommandChanged)));

        /// <summary>
        /// Gets the HyperlinkCommand property. This dependency property 
        /// indicates ....
        /// </summary>
        public static ICommand GetHyperlinkCommand(DependencyObject d)
        {
            return (ICommand)d.GetValue(HyperlinkCommandProperty);
        }

        /// <summary>
        /// Sets the HyperlinkCommand property. This dependency property 
        /// indicates ....
        /// </summary>
        public static void SetHyperlinkCommand(DependencyObject d, ICommand value)
        {
            d.SetValue(HyperlinkCommandProperty, value);
        }

        /// <summary>
        /// Handles changes to the HyperlinkCommand property.
        /// </summary>
        private static void OnHyperlinkCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            FrameworkElement fe = (FrameworkElement)d;

            if (e.OldValue != null && e.NewValue != null)
                return;

            if (e.OldValue != null)
            {
                fe.RemoveHandler(Hyperlink.ClickEvent, new RoutedEventHandler(HookClick));
            }

            if (e.NewValue != null)
            {
                fe.AddHandler(Hyperlink.ClickEvent, new RoutedEventHandler(HookClick));
            }
        }

        #endregion

        private static void HookClick(object sender, RoutedEventArgs e)
        {
            GetHyperlinkCommand((DependencyObject)sender).Execute(null);
        }
    }
}
